package com.ciaojian.client.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ciaojian.core.config.FuluOpenConfig;
import com.ciaojian.core.enums.sys.StatusCode;
import com.ciaojian.core.mapper.CouponCodeMapper;
import com.ciaojian.core.mapper.DFulugoodsMapper;
import com.ciaojian.core.mapper.OrderMapper;
import com.ciaojian.core.mapper.PhoneCreditMapper;
import com.ciaojian.core.model.CouponCode;
import com.ciaojian.core.model.DFulugoods;
import com.ciaojian.core.model.Order;
import com.ciaojian.core.model.PhoneCredit;
import com.ciaojian.core.model.fulu.*;
import com.ciaojian.core.model.vo.PhoneCreditVo;
import com.ciaojian.core.service.PhoneCreditService;
import com.ciaojian.core.util.FuluUtil;
import com.ciaojian.core.util.JsonUtil;
import com.ciaojian.core.util.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author oxiny
 */
@Service
public class PhoneCreditServiceImpl<M extends BaseMapper<T>, T> extends PhoneCreditService<PhoneCreditMapper, PhoneCredit> {

    @Resource
    private PhoneCreditMapper phoneCreditMapper;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private CouponCodeMapper couponCodeMapper;

    @Resource
    private DFulugoodsMapper dFulugoodsMapper;


    @Transactional(rollbackFor = Exception.class)
    public Result adminFuluMoblieAdd(PhoneCreditVo phoneCreditVo) {
        if ("mufc"==phoneCreditVo.getMsg()){
            return Result.ok("系统错误");
        }
        if (ObjectUtil.isNotNull(phoneCreditVo.getId())){
            PhoneCredit phoneCredit = phoneCreditMapper.selectById(phoneCreditVo.getId());

            Order order = orderMapper.selectById(phoneCredit.getOrderId());

            String orderJson = "{\"customer_order_no\": \"" + order.getOrderNo() + "\"}";
            FuluRequest orderJsonRequest = FuluUtil.newFuluRequest(orderJson, FuluOpenConfig.ORDERINFO_GET_METHOD, FuluOpenConfig.APP_KEY, FuluOpenConfig.SYSSECRET);
            String orderfulu = JsonUtil.toJson(orderJsonRequest);
            String post = HttpUtil.post(FuluOpenConfig.FULU_PROD_URL, orderfulu);
            FuluResponse fuluResponse1 = JsonUtil.fromJson(post, FuluResponse.class);

            OrderInfo orderInfo = JsonUtil.fromJson(fuluResponse1.getResult(), OrderInfo.class);

            phoneCredit.setTradeNo(orderInfo.getOrder_id());
            if (orderInfo.getOrder_state().equals("success")) {
                phoneCredit.setStatus(1);
                return Result.ok("充值成功",orderInfo);
            }
            if (orderInfo.getOrder_state().equals("processing") || orderInfo.getOrder_state().equals("untreated")) {
                phoneCredit.setStatus(2);
                return Result.ok("充值中,请等待",orderInfo);
            }
            if (orderInfo.getOrder_state().equals("failed")) {
                phoneCredit.setStatus(0);
                return Result.ok("充值失败,请重新充值,",orderInfo);
            }

        }else {
            QueryWrapper<PhoneCredit> phoneCreditQueryWrapper = new QueryWrapper<>();
            phoneCreditQueryWrapper.eq("code",phoneCreditVo.getCode());
            PhoneCredit phoneCredit = phoneCreditMapper.selectOne(phoneCreditQueryWrapper);

            if (ObjectUtil.isNotNull(phoneCredit)){
                phoneCredit.setRechargeTime(new Date());
                phoneCredit.setUserPhone(phoneCreditVo.getUserPhone());
                Order order = orderMapper.selectById(phoneCredit.getOrderId());


                QueryWrapper<CouponCode> codeQueryWrapper = new QueryWrapper<>();
                codeQueryWrapper.eq("outside_code",phoneCreditVo.getCode());
                CouponCode couponCode = couponCodeMapper.selectOne(codeQueryWrapper);
                couponCode.setStatus(2);
                couponCodeMapper.updateById(couponCode);

                //充值请求
                //基础参数
                DirectAdd directAdd = new DirectAdd();
                //福禄商品
                QueryWrapper<DFulugoods> fuluqw = new QueryWrapper<>();
                fuluqw.eq("coupon_id", couponCode.getCouponId());
                DFulugoods dFulugoods = dFulugoodsMapper.selectOne(fuluqw);

                Assert.isTrue(ObjectUtil.isNotEmpty(dFulugoods), "暂时无法充值,请稍后01");

                if (dFulugoods.getStatus() != 0 && dFulugoods.getFuluStatus() != 0 && dFulugoods.getStockStatus() != 0) {
                    Assert.notNull(null, "暂时无法充值,请稍后02");
                }
                directAdd.setProduct_id(dFulugoods.getFuluGoodsId());

                String orderNo = order.getOrderNo()+phoneCreditVo.getOrderLast();     ///////这里要改 +"里面加数字"   新订单号

                directAdd.setCustomer_order_no(orderNo);
                directAdd.setCharge_account(phoneCreditVo.getUserPhone());
                directAdd.setBuy_num(1);
                directAdd.setContact_tel(phoneCreditVo.getUserPhone());
                directAdd.setExternal_biz_id(order.getId().toString());
                String directAddJson = JsonUtil.toJson(directAdd);
                //封装请求参数 请求fulu (正式)
                FuluRequest fuluRequest = FuluUtil.newFuluRequest(directAddJson, FuluOpenConfig.DIRECT_ADD_METHOD, FuluOpenConfig.APP_KEY, FuluOpenConfig.SYSSECRET);
                String fuluRequestJson = JsonUtil.toJson(fuluRequest);
                String fuluResponseJson = HttpUtil.post(FuluOpenConfig.FULU_PROD_URL, fuluRequestJson);
                FuluResponse fuluResponse = JsonUtil.fromJson(fuluResponseJson, FuluResponse.class);
                //充值请求成功
                if (fuluResponse.getCode() == 0) {
                    String result = fuluResponse.getResult();
                    DirectAddResponse directAddResponse = JsonUtil.fromJson(result, DirectAddResponse.class);

                    String orderJson = "{\"customer_order_no\": \"" + orderNo + "\"}";
                    FuluRequest orderJsonRequest = FuluUtil.newFuluRequest(orderJson, FuluOpenConfig.ORDERINFO_GET_METHOD, FuluOpenConfig.APP_KEY, FuluOpenConfig.SYSSECRET);
                    String orderfulu = JsonUtil.toJson(orderJsonRequest);
                    String post = HttpUtil.post(FuluOpenConfig.FULU_PROD_URL, orderfulu);
                    FuluResponse fuluResponse1 = JsonUtil.fromJson(post, FuluResponse.class);

                    OrderInfo orderInfo = JsonUtil.fromJson(fuluResponse1.getResult(), OrderInfo.class);

                    phoneCredit.setTradeNo(directAddResponse.getOrder_id());
                    if (orderInfo.getOrder_state().equals("success")) {
                        phoneCredit.setStatus(1);
                        phoneCredit.setRemark("内部新订单号:"+orderNo);
                        phoneCreditMapper.updateById(phoneCredit);
                        return Result.ok("充值成功",fuluResponse);
                    }
                    if (orderInfo.getOrder_state().equals("processing") || orderInfo.getOrder_state().equals("untreated")) {
                        phoneCredit.setStatus(2);
                        phoneCredit.setRemark("内部新订单号:"+orderNo);
                        phoneCreditMapper.updateById(phoneCredit);
                        return Result.ok("充值受理中",fuluResponse);
                    }
                    if (orderInfo.getOrder_state().equals("failed")) {
                        phoneCredit.setStatus(0);
                        phoneCredit.setRemark("内部新订单号:"+orderNo);
                        phoneCreditMapper.updateById(phoneCredit);
                        return Result.ok("充值失败中",fuluResponse);
                    }
                }
            }

        }
        return Result.ok("订单失败,请检查代码");
    }

    @Transactional(rollbackFor = Exception.class)
    public Result requestFuluMoblieAdd(PhoneCreditVo phoneCreditVo){
        try {
            if (ObjectUtil.isNull(phoneCreditVo.getUserPhone())){
                return Result.error("充值账号格式不正确");
            }

            // 判断券码是否已经使用过
            boolean flag = this.lambdaQuery()
                    .eq(PhoneCredit::getCode, phoneCreditVo.getCode())
                    .count() == 0;
            Assert.isTrue(flag, "此券已使用");

            Order order = orderMapper.selectById(phoneCreditVo.getOrderId());

            QueryWrapper<CouponCode> codeQueryWrapper = new QueryWrapper<>();
            codeQueryWrapper.eq("outside_code",phoneCreditVo.getCode());
            CouponCode couponCode = couponCodeMapper.selectOne(codeQueryWrapper);
            couponCode.setStatus(2);
            couponCodeMapper.updateById(couponCode);

            //封装话费券表
            PhoneCredit phoneCredit = new PhoneCredit();
            phoneCredit.setUserId(phoneCreditVo.getUserId());
            phoneCredit.setUserPhone(phoneCreditVo.getUserPhone());
            phoneCredit.setCode(phoneCreditVo.getCode());
            phoneCredit.setOrderId(phoneCreditVo.getOrderId());
            phoneCredit.setStatus(phoneCreditVo.getStatus());
            phoneCredit.setRechargeTime(phoneCreditVo.getRechargeTime());
            phoneCredit.setRequestsNum(1);
            try {

                //基础参数
                DirectAdd directAdd = new DirectAdd();


                //福禄商品
                QueryWrapper<DFulugoods> fuluqw = new QueryWrapper<>();
                fuluqw.eq("coupon_id", couponCode.getCouponId());
                DFulugoods dFulugoods = dFulugoodsMapper.selectOne(fuluqw);

                Assert.isTrue(ObjectUtil.isNotEmpty(dFulugoods), "暂时无法充值,请稍后01");

                if (dFulugoods.getStatus() != 0 && dFulugoods.getFuluStatus() != 0 && dFulugoods.getStockStatus() != 0) {
                    Assert.notNull(null, "暂时无法充值,请稍后02");
                }


                directAdd.setProduct_id(dFulugoods.getFuluGoodsId());

                directAdd.setCustomer_order_no(order.getOrderNo());
                directAdd.setCharge_account(phoneCreditVo.getUserPhone());
                directAdd.setBuy_num(1);
                directAdd.setContact_tel(phoneCreditVo.getUserPhone());
                directAdd.setExternal_biz_id(order.getId().toString());
                String directAddJson = JsonUtil.toJson(directAdd);

                //封装请求参数 请求fulu (正式)
                FuluRequest fuluRequest = FuluUtil.newFuluRequest(directAddJson, FuluOpenConfig.DIRECT_ADD_METHOD, FuluOpenConfig.APP_KEY, FuluOpenConfig.SYSSECRET);
                String fuluRequestJson = JsonUtil.toJson(fuluRequest);
                String fuluResponseJson = HttpUtil.post(FuluOpenConfig.FULU_PROD_URL, fuluRequestJson);

                // (测试沙箱)
//            FuluRequest fuluRequest = FuluUtil.newFuluRequest(directAddJson,FuluOpenConfig.DIRECT_ADD_METHOD,FuluOpenConfig.APP_KEY_TEST,FuluOpenConfig.SYSSECRET_TEST);
//            String fuluRequestJson = JsonUtil.toJson(fuluRequest);
//            String fuluResponseJson = HttpUtil.post(FuluOpenConfig.FULU_TEST_URL, fuluRequestJson);

                FuluResponse fuluResponse = JsonUtil.fromJson(fuluResponseJson, FuluResponse.class);
                //充值请求成功
                if (fuluResponse.getCode() == 0) {
                    String result = fuluResponse.getResult();
                    DirectAddResponse directAddResponse = JsonUtil.fromJson(result, DirectAddResponse.class);

                    String orderJson = "{\"customer_order_no\": \"" + order.getOrderNo() + "\"}";
                    FuluRequest orderJsonRequest = FuluUtil.newFuluRequest(orderJson, FuluOpenConfig.ORDERINFO_GET_METHOD, FuluOpenConfig.APP_KEY, FuluOpenConfig.SYSSECRET);
                    String orderfulu = JsonUtil.toJson(orderJsonRequest);
                    String post = HttpUtil.post(FuluOpenConfig.FULU_PROD_URL, orderfulu);
                    FuluResponse fuluResponse1 = JsonUtil.fromJson(post, FuluResponse.class);

                    OrderInfo orderInfo = JsonUtil.fromJson(fuluResponse1.getResult(), OrderInfo.class);

                    phoneCredit.setTradeNo(directAddResponse.getOrder_id());
                    if (orderInfo.getOrder_state().equals("success")) {
                        phoneCredit.setStatus(1);
                    }
                    if (orderInfo.getOrder_state().equals("processing") || orderInfo.getOrder_state().equals("untreated")) {
                        phoneCredit.setStatus(2);
                    }
                    if (orderInfo.getOrder_state().equals("failed")) {
                        phoneCredit.setStatus(0);
                    }
                }else {
                    phoneCredit.setRemark(Integer.toString(fuluResponse.getCode()));
                }
            }catch (Exception e){
                System.out.println("fulu-->"+e.getMessage());
            }

            phoneCreditMapper.insert(phoneCredit);

            return Result.ok("充值中请稍后");
        }catch (Exception e){
            return Result.fail(StatusCode.FAIL,e.getMessage());
        }
    }


    public static boolean isMobileNO(String mobile){
        if (mobile.length() != 11)
        {
            return false;
        }else{
            /**
             * 移动号段正则表达式
             */
            String pat1 = "^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
            /**
             * 联通号段正则表达式
             */
            String pat2  = "^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
            /**
             * 电信号段正则表达式
             */
            String pat3  = "^((133)|(153)|(177)|(18[0,1,9])|(149))\\d{8}$";
            /**
             * 虚拟运营商正则表达式
             */
            String pat4 = "^((170))\\d{8}|(1718)|(1719)\\d{7}$";
            Pattern pattern1 = Pattern.compile(pat1);
            Matcher match1 = pattern1.matcher(mobile);
            boolean isMatch1 = match1.matches();
            if(isMatch1){
                return true;
            }
            Pattern pattern2 = Pattern.compile(pat2);
            Matcher match2 = pattern2.matcher(mobile);
            boolean isMatch2 = match2.matches();
            if(isMatch2){
                return true;
            }
            Pattern pattern3 = Pattern.compile(pat3);
            Matcher match3 = pattern3.matcher(mobile);
            boolean isMatch3 = match3.matches();
            if(isMatch3){
                return true;
            }
            Pattern pattern4 = Pattern.compile(pat4);
            Matcher match4 = pattern4.matcher(mobile);
            boolean isMatch4 = match4.matches();
            if(isMatch4){
                return true;
            }
            return false;
        }
    }
}
